import logging
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

# 映射表：带重音字母映射到不带重音字母
accent_mapping = {
    'á': 'a', 'é': 'e', 'í': 'i', 'ó': 'o', 'ú': 'u', 'ü': 'u', 'ñ': 'n',
    'Á': 'a', 'É': 'e', 'Í': 'i', 'Ó': 'o', 'Ú': 'u', 'Ü': 'u', 'Ñ': 'n'
}


# 辅助函数：替换字符串中的带重音字母
def replace_accents(s):
    return ''.join(accent_mapping.get(c, c) for c in s)


# 转换为小写并替换带重音的字母
def normalize_city_name(name):
    return replace_accents(name.lower())


class RPBackdoorDeal231120(object):

    @classmethod
    def csv_import_for_spain_postal_code(cls, env, csv_reader, headers):
        """ csv文件导入，获取西班牙邮编 """
        for csv in csv_reader:
            print(csv)
            # 1、获取数据
            _country_name = csv[0] if csv[0] else False
            _province_name = csv[1] if csv[1] else False
            _city_name = csv[2] if csv[2] else False
            _local_name = csv[3] if csv[3] else False
            _postal_code_name = csv[4] if csv[4] else False
            # 2、数据处理
            _country_name = '西班牙' if _country_name == 'Spain' else _country_name
            # 3、寻找国家
            country_rcd = env['res.country'].search([('name', '=', _country_name)], limit=1)
            if not country_rcd:
                raise UserError('没有获取到国家')
            # 4、寻找省份
            state_rcd = env['res.country.state'].search([('name', 'ilike', "%{}%".format(_province_name)), ('country_id', '=', country_rcd.id)], limit=1)
            if not state_rcd:
                # state_rcd = self.env["res.country.state"].create({'name': _province_name, 'country_id': country_rcd.id})
                raise UserError('没有获取到省份')
            # 5、寻找或创建市区
            city_rcd = env['res.city'].search([('name', '=', _city_name), ('country_id', '=', country_rcd.id), ('state_id', '=', state_rcd.id)], limit=1)
            if not city_rcd:
                city_rcd = env['res.city'].create({'name': _city_name, 'country_id': country_rcd.id, 'state_id': state_rcd.id})
            # 6、寻找或创建区县
            if _local_name:
                county_rcd = env['res.county'].search([('name', '=', _local_name), ('country_id', '=', country_rcd.id), ('state_id', '=', state_rcd.id), ('city_id', '=', city_rcd.id)])
                if not county_rcd:
                    county_rcd = env['res.county'].create({'name': _local_name, 'country_id': country_rcd.id, 'state_id': state_rcd.id, 'city_id': city_rcd.id})
            else:
                county_rcd = False
            # 7、寻找或创建邮编
            postal_code_rcd = env['rp.postal.code'].search([('name', '=', _postal_code_name), ('country_id', '=', country_rcd.id), ('state_id', '=', state_rcd.id), ('city_id', '=', city_rcd.id)])
            if not postal_code_rcd:
                postal_code_rcd = env['rp.postal.code'].create({'name': _postal_code_name, 'country_id': country_rcd.id, 'state_id': state_rcd.id, 'city_id': city_rcd.id})
            # 给邮编填充区县
            if county_rcd:
                postal_code_rcd.write({'county_ids': [(4, county_rcd.id)]}) if county_rcd.id not in postal_code_rcd.county_ids.ids else False

            print(country_rcd, state_rcd, city_rcd, postal_code_rcd)

    @classmethod
    def spain_city_combine(cls, env):
        """ 处理西班牙市区由于为区分重音辅音导致的重复数据 """

        # 两条记录的合并
        def combine_postal_code(id1, id2):
            rcd1 = env['rp.postal.code'].search([('id', '=', id1)])
            rcd2 = env['rp.postal.code'].search([('id', '=', id2)])
            # 1、名称合并
            city_rcd1 = rcd1.city_id
            city_rcd2 = rcd2.city_id
            # city_rcd1.name = city_rcd1.name + ' (' + city_rcd2.name + ')'
            # 2、邮编区域合并
            county1_ids = rcd1.county_ids.ids
            county2_ids = rcd2.county_ids.ids
            rcd1.write({'county_ids': [(6, 0, county1_ids + county2_ids)]})
            # 3、区县改关联市
            county2_rcds = env['res.county'].search([('city_id', '=', city_rcd2.id)])
            for cr in county2_rcds:
                cr.write({'city_id': city_rcd1.id})
            print(rcd1.id, rcd1.name, rcd1.city_id.name, rcd1.county_ids.ids)
            print(rcd2.id, rcd2.name, rcd2.city_id.name, rcd2.county_ids.ids)
            # 4、删除rcd2,city_rcd2
            # return rcd1.id,rcd2.id
            return {'city1_rcd': city_rcd1,
                    'city1_name': city_rcd1.name + ' (' + city_rcd2.name + ')',  # 最后统一换名
                    'rcd2_id': rcd2.id,  # 删除邮编
                    'city2_id': city_rcd2.id}  # 删除城市

        cities_group = env['rp.postal.code'].read_group(domain=[('country_id', '=', 68)], fields=['name', 'id:count'], groupby=['name'], orderby='name ASC')
        unlink_postal_code_id_list, unlink_city_id_list, rewrite_city_name = [], [], []
        for cg in cities_group:
            # print(cg)
            if cg.get('name_count') > 1 and cg.get('name') != 'Spain ZIP Code':
                cities_rcds = env['rp.postal.code'].search(cg.get('__domain'))
                name_to_ids = {}
                for cr in cities_rcds:
                    normalized_name = normalize_city_name(cr.city_id.name)
                    if normalized_name in name_to_ids:
                        name_to_ids[normalized_name].append(cr.id)
                    else:
                        name_to_ids[normalized_name] = [cr.id]

                # 查找并返回有重复名称的城市记录的 ID
                duplicate_ids = []
                for ids in name_to_ids.values():
                    if len(ids) > 1:
                        duplicate_ids.extend(ids)

                if duplicate_ids:
                    print("-------------------------------------------------------------")
                    for i in range(0, len(duplicate_ids), 2):
                        result_dict = combine_postal_code(duplicate_ids[i], duplicate_ids[i + 1])
                        unlink_postal_code_id_list.append(result_dict['rcd2_id'])
                        unlink_city_id_list.append(result_dict['city2_id'])
                        rewrite_city_name.append(result_dict)

        unlink_postal_code_id_list = list(set(unlink_postal_code_id_list))
        print('unlink_postal_code_id_list:', unlink_postal_code_id_list)
        unlink_postal_code_rcds = env['rp.postal.code'].search([('id', 'in', unlink_postal_code_id_list)])
        unlink_postal_code_rcds.unlink()

        unlink_city_id_list = list(set(unlink_city_id_list))
        print('unlink_city_id_list:', unlink_city_id_list)
        unlink_city_rcds = env['res.city'].search([('id', 'in', unlink_city_id_list)])
        unlink_city_rcds.unlink()

        for rcn in rewrite_city_name:
            rcn['city1_rcd'].write({'name': rcn['city1_name']})

    @classmethod
    def spain_county_combine(cls, env):
        """ 处理西班牙区县由于为区分重音辅音导致的重复数据 """

        county_group = env['res.county'].read_group(domain=[('country_id', '=', 68)], fields=['name', 'city_id', 'id:count'], groupby=['city_id'], orderby='name ASC')

        for cg in county_group:
            county_rcds = env['res.county'].search(cg.get('__domain'))
            name_to_ids = {}
            for cr in county_rcds:
                normalized_name = normalize_city_name(cr.name)
                if normalized_name in name_to_ids:
                    name_to_ids[normalized_name].append(cr.id)
                else:
                    name_to_ids[normalized_name] = [cr.id]

            # 查找并返回有重复名称的城市记录的 ID
            duplicate_ids = []
            for ids in name_to_ids.values():
                if len(ids) > 1:
                    duplicate_ids.extend(ids)

            if duplicate_ids:
                print("-------------------------------------------------------------")
                for i in range(0, len(duplicate_ids), 2):
                    county1_rcd = env['res.county'].search([('id', '=', duplicate_ids[i])])
                    print(county1_rcd.id, county1_rcd.name)
                    county2_rcd = env['res.county'].search([('id', '=', duplicate_ids[i + 1])])
                    print(county2_rcd.id, county2_rcd.name)
                    county2_rcd.unlink()

    @classmethod
    def spain_city_ElxElche(cls, env):
        """ 处理西班牙邮编Elx-Elche城市重复问题 """
        city1_rcd = env['res.city'].search([('name', '=', 'Elx-Elche')])
        city2_rcd = env['res.city'].search([('name', '=', 'Elx/elche')])
        # 删除city2下属区县
        county_rcds = env['res.county'].search([('city_id', '=', city2_rcd.id)])
        county_rcds.unlink()
        # 删除city2邮编
        postal_code_rcds = env['rp.postal.code'].search([('city_id', '=', city2_rcd.id)])
        postal_code_rcds.unlink()
        # 删除city2
        city2_rcd.unlink()

    @classmethod
    def unlink_province(cls, env):
        """ 清掉除西班牙外所有省份 """
        spain = env['res.country'].search([('code', '=', 'ES')], limit=1)
        province_rcds = env['res.country.state'].search([('country_id', '!=', spain.id)])
        province_rcds.unlink()

    @classmethod
    def csv_import_for_europe_postal_code(cls, env, csv_reader, headers):
        """ 欧盟27国邮编导入，除西班牙 """
        error_list = []
        for csv in csv_reader:
            # print(csv)
            # 1、获取数据
            # countryName, countryCode, adminName1, adminCode1, adminName2, adminCode2
            # adminName3, adminCode3, placeName, postalCode, accuracy, latitude, longitude
            _country_name = csv[0] if csv[0] else False
            _country_code = csv[1] if csv[1] else False
            _province_name = csv[4] if csv[4] else False
            _province_code = csv[5] if csv[5] else False
            _city_name = csv[8] if csv[8] else False
            _postal_code_name = csv[9] if csv[9] else False
            print(_country_name, _country_code, _province_name, _province_code, _city_name, _postal_code_name)
            if _country_code != 'ES':
                if all([_country_name, _country_code, _province_name, _city_name, _postal_code_name]):
                    # 3、寻找国家
                    country_rcd = env['res.country'].search([('code', '=', _country_code)], limit=1)
                    if not country_rcd:
                        raise UserError('没有获取到国家')
                    # 4、寻找或创建省份
                    state_rcd = env['res.country.state'].search([('name', 'ilike', "%{}%".format(_province_name)), ('country_id', '=', country_rcd.id)], limit=1)
                    if not state_rcd:
                        state_rcd = env["res.country.state"].create({'name': _province_name, 'country_id': country_rcd.id})
                    # 5、寻找或创建市区
                    city_rcd = env['res.city'].search([('name', '=', _city_name), ('country_id', '=', country_rcd.id), ('state_id', '=', state_rcd.id)], limit=1)
                    if not city_rcd:
                        city_rcd = env['res.city'].create({'name': _city_name, 'country_id': country_rcd.id, 'state_id': state_rcd.id})
                    # 6、寻找或创建邮编
                    postal_code_rcd = env['rp.postal.code'].search([('name', '=', _postal_code_name), ('country_id', '=', country_rcd.id), ('state_id', '=', state_rcd.id), ('city_id', '=', city_rcd.id)])
                    if not postal_code_rcd:
                        postal_code_rcd = env['rp.postal.code'].create({'name': _postal_code_name, 'country_id': country_rcd.id, 'state_id': state_rcd.id, 'city_id': city_rcd.id})

                    print(country_rcd, state_rcd, city_rcd, postal_code_rcd)
                else:
                    error_list.append(_postal_code_name)




